package com.hx0311.pas.security.user.webapp;

import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.hx0311.core.dao.support.ResultSetUtil;
import com.hx0311.core.webapp.struts2.action.BaseAction;
import com.hx0311.pas.PasConstants;
import com.hx0311.pas.SysUtil;
import com.hx0311.pas.security.user.dao.UserDao;
import com.hx0311.pas.security.user.model.User;

@SuppressWarnings( { "unchecked", "serial" })
public class UserAction extends BaseAction<User, UserDao> {

	private UserDao dao;

	@Override
	public String edit() {
		if (StringUtils.isNotBlank(getModel().getXcrbh())) {
			Map data = getDao().get(getModel().getXcrbh());
			User user = new User();
			ResultSetUtil.copyMapValues(user, data);
			setModel(user);
		}
		return INPUT;
	}

	@Override
	public String index() {
		items = getDao().getAll();
		return SUCCESS;
	}

	@Override
	public String remove() {
		if (StringUtils.isNotBlank(getModel().getXcrbh())) {
			getDao().remove(getModel().getXcrbh());
		}
		return INDEX;
	}

	@Override
	public String save() {
		if (ADD.equals(getOptionType())) {
			getDao().add(getModel());
		} else {
			if (PasConstants.VIEW_PWD.equals(getModel().getMm())) {
				getModel().setMm(
						(String) getDao().get(getModel().getXcrbh()).get("MM"));
			}
			getDao().update(getModel());
		}
		return INDEX;
	}

	@Override
	public UserDao getDao() {
		if (dao == null) {
			dao = new UserDao();
		}
		return dao;
	}

	public String chkLogin() {
		String xcrbh = this.getRequest().getParameter("userName");
		String mm = this.getRequest().getParameter("password");
		User user = getDao().getUser(xcrbh, mm);
		if (user != null) {
			getRequest().getSession().setAttribute(PasConstants.USER_IN_SESSION, user);
			return SUCCESS;
		} else {
			addActionError("用户名密码错误!");
			return ERROR;
		}
	}

	/**
	 * 获得机构定义
	 * 
	 * @return
	 */
	public Map getJgdys() {
		return SysUtil.getJgdyMap(getServletContext());
	}

	/**
	 * 获得人员类别
	 * 
	 * @return
	 */
	public Map getRylbs() {
		return SysUtil.getRylbMap(getServletContext());
	}
}
